package com.itheima.demo7;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo2 {
    public static void main(String[] args) throws IOException {
        //TCP协议，接收数据

        //1.创建对象ServerSocker
        ServerSocket ssc = new ServerSocket(10086);

        //2.监听客户端的连接
        Socket socket = ssc.accept();

        //3.从连接通道中获取输入流读取的数据
        //创建字符缓冲流进行数据读取
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        int b;

        //细节：read方法会一直从通道中读取数据，需要有一个结束标记才会停止运行
        while ((b = br.read()) != -1) {
            System.out.print((char) b);
        }

        //回写数据
        //4.从连接通道中获取输出流写出数据
        OutputStream os = socket.getOutputStream();
        //写出数据(通过字节数组的形式)
        os.write("有多高兴？".getBytes());


        //5.释放资源
        socket.close();
        ssc.close();


    }
}
